package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
//    @Value("reggie.path")
    public String filedir;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {


        //获取文件名
        String filename1 = file.getOriginalFilename();

        //获取扩展名
        String substring = filename1.substring(filename1.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
       String filename= UUID.randomUUID().toString()+substring;

       //将上传文件保存到服务器
//        System.out.println("=================================");
//        System.out.println(filedir);
//        System.out.println("=================================");
        File  uploadfile=new File(filedir,filename);

       //将上传文件保存到指定位置
        file.transferTo(uploadfile);

        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name,HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        //将文件名读取到程序中
        File sourceFile = new File(filedir + name);
        FileInputStream inputStream = new FileInputStream(sourceFile);
//        System.out.println("=================================");
//        System.out.println(name);
//        System.out.println("=================================");
        //获取向浏览器响应的输出流
        ServletOutputStream outputStream = response.getOutputStream();

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }

        //关闭资源
        outputStream.close();
        inputStream.close();

    }

}
